package com.example.spring.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.example.spring.model.User;

@Repository
public class UserDAOImpl implements UserDAO{
	
	@Autowired
    private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}
  
    @SuppressWarnings("unchecked")
	public List<User> getUser(String login) {  
    	Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
        List<User> userList = null;
        try{
        	Query query = session.createQuery("from User u where u.userName = :login");  
            query.setParameter("login", login);  
            userList = query.list();  
        }
        catch(HibernateException e){
			e.printStackTrace();
			if(transaction != null){
				transaction.rollback();
			}
		}
		finally{
			if(session != null){
				session.close();
			}
		}
        if (userList.size() > 0)  
            return userList;  
        else  
            return null;      
    }  
}
